﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace G.Net.APISuite
{
    /// <summary>
    /// 无签名请求
    /// </summary>
    public class SampleClient : IClient
    {
        /// <summary>
        /// 默认使用Json解析
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<T> Execute<T>(Request<T> request) where T : IResponse
        {
            HttpRequest req = null;
            if (request.RequestMethod == System.Net.Http.HttpMethod.Get)
            {
                HttpGet get = new HttpGet(request.Path);
                foreach (var item in request.GetParameters())
                {
                    if (!string.IsNullOrEmpty(item.Value))
                         get.Params.Add(item.Key, item.Value);
                }
                req = get;
            }
            T obj;
            var result = await req.RequestAsync();
            if (result.Exception == null)
                obj = Utils.SerializerHelp.JsonDeserialize<T>(result.Result);
            else
            {
                obj = Activator.CreateInstance<T>();
                obj.Exception = result.Exception;
            }
            obj.Body = result.Result;
            return obj;
        }
    }
}
